"use strict";
/**
 * @author wangchenzhao
 * @date 2018/11/20
 */
const fs = require('fs');
const moment = require('moment');
const uuid = require('uuid/v1');
const jwt = require('jwt-simple');
const crypto = require('crypto');

module.exports = {
    /**
     * 文件读取
     * @param path
     * @returns {Promise<any>}
     */
    readFile(path) {
        return new Promise((resolve, reject) => {
            fs.readFile(path, (err, result) => {
                if (err) {
                    reject(err);
                }
                resolve(result);
            });
        });
    },

    /**
     *  日期处理
     */
    moment: moment,

    /**
     * uuid
     * @returns {string | *}
     */
    uuid: function () {
        let uuid = uuid();
        uuid = uuid.replace(/-/g, "").toUpperCase();
        return uuid;
    },

    /**
     * 生成随机数
     * @param min
     * @param max
     * @returns {string}
     */
    getRandomCode: function (min, max) {
        var code = Math.floor(Math.random() * (max - min + 1) + min);
        return code.toString();
    },

    /**
     * post json请求
     * @param url
     * @param data
     * @returns {Promise<*>}
     */
    async postJson(url, data) {
        const {ctx} = this;
        let result = await ctx.curl(url, {method: 'POST', contentType: 'json', dataType: 'json', data});
        return result.data;
    },

    /**
     * md5密码加密
     * @param password
     * @returns {string}
     */
    md5Pwd(password) {
        let md5Pwd = crypto.createHash('md5').update(password).digest('hex');
        return md5Pwd;
    },

    /**
     * jwt Secret
     */
    jwtSecret: 'jstSecret',

    /**
     * 创建token
     * @param data    数据
     * @param minutes 分钟 默认  24 * 60 * 30 30天
     * @param iss     jwt签发者
     * @returns {string | Uint8Array | void}
     */
    createToken(data, minutes = 24 * 60 * 30, iss = 'xgkj') {
        let expires = moment().add(minutes, 'minutes').valueOf();
        let token = jwt.encode({
            iss: iss,
            exp: expires,
            data: data
        }, this.jwtSecret);
        return token;
    },

    /**
     * 检查token
     * @param token
     * @returns {*}
     */
    checkToken(token) {
        const {ctx} = this;
        const {resMsg, enumResType} = ctx;
        if (!token) {
            return resMsg.newError(enumResType.token_err_code, "token为空");
        }
        let decoded = jwt.decode(token, this.jwtSecret);
        if (decoded.exp <= Date.now()) {
            return resMsg.newError(enumResType.token_err_code, "token已过期");
        }
        return resMsg.newOk(decoded.data);
    },
}